#include <stdio.h>
#include <string.h>

#define MAXLEN 1000
#define MAXLINES 10000

#define ALLOCSIZE 10000

static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;

char *alloc(int n)
{
    if(allocbuf + ALLOCSIZE - allocp >= n)
    {
        allocp += n;
        return allocp - n; 
    }
    else
    {
        return 0;
    }    
}

void afree(char *p)
{
    if(p >= allocbuf && p < allocbuf + ALLOCSIZE)
        allocp = p;
}

int getline2(char line[], int maxline)
{
    int c, i;

    for (i = 0; i < maxline - 1 && (c = getchar()) != EOF && c != '\n'; i++)
    {
        line[i] = c;
    }
    if (c == '\n')
    {
        line[i] = c;
        i++;
    }
    line[i] = '\0';
    return i;
}

int readlines(char *lineptr[], int maxlines)
{
    int len, nlines;
    char *p, line[MAXLEN];
    nlines = 0;

    while ((len = getline2(line, MAXLEN)) > 0)
    {
        if(nlines >= maxlines || (p = alloc(len)) == NULL)
            return -1;
        else
        {
            line[len - 1] = '\0';
            strcpy(p, line);
            lineptr[nlines++] = p;
        }        
    }
    return nlines;
}

int main(int argc, char *argv[])
{
    char *plines[MAXLINES];
    int nlines, n;

    if(argc == 2) 
    {
        n = (*(argv + 1))[1] - '0';
        printf("n = %d\n", n);
    }       
    else
    {
        n = 10;
        printf("Usage: tail -n\n");
        printf("Default: n = 10\n");
    }
    
    nlines = readlines(plines, MAXLINES);
    if(n > nlines)
    {
        printf("input max lines is %d\n", nlines);
        n = nlines;
    }

    if(nlines > 0)
    {
        while (n > 0)
        {
            printf("%s\n", plines[nlines - n]);
            n--;
        }        
    }
    
    return 0;
}
